package rabbitmq

import (
	util "gin-easy/pkg/until"
	"log"
)

// 消费者
func Recive(queueName string) {
	qn := QuenuList[queueName]
	q, err := RabbitmqCh.QueueDeclare(
		qn.name,       // name
		qn.durable,    // durable
		qn.autoDelete, // delete when unused
		qn.exclusive,  // exclusive
		qn.nowWait,    // no-wait
		qn.args,       // arguments
	)
	failOnError(err, "Failed to declare a queue")

	err = RabbitmqCh.Qos(
		1,     // prefetch count
		0,     // prefetch size
		false, // global
	)
	failOnError(err, "Failed to set QoS")

	msgs, err := RabbitmqCh.Consume(
		q.Name, // queue
		"",     // consumer
		false,  // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	failOnError(err, "Failed to register a consumer")

	forever := make(chan bool)
	if msgs != nil {
		go func() {
			for d := range msgs {
				log.Printf("Received a message: %s", d.Body)
				d1 := util.ByteToMap(d.Body)
				task1 := TaskList[d1["taskName"]]
				if task1.action != nil {
					r := task1.action(d1["data"])
					if r {
						d.Ack(false)
					}
				} else {
					d.Ack(false) //
				}

			}
		}()
	}

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}
